package com.test.mess;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class JavaDownloadFileFromURL {

    private static LocalDate now = LocalDate.now();
    private static String date = now.format(DateTimeFormatter.ofPattern("yy-MM"));
    private static String baseDir = "D:\\dl\\" + date;


    static String imageUrl = "";
    static String fileName = "";

    public static void main(String[] args) {
        try {
            Path jsonPath = Paths.get("D:\\dl\\list.txt");
            Scanner scanner = new Scanner(jsonPath);
            int total = 0;
            String line = "";
            while (scanner.hasNextLine()) {
                line = scanner.next();
                System.out.println("处理：" + line);
                if (line == null || line.trim().equals("")) {
                    break;
                }
                imageUrl = line.split(",")[0];
                fileName = line.split(",")[1];
                if (fileName == null || fileName.trim().equals("")) {
                    continue;
                }
                new Thread(() -> downloadUsingNIO(imageUrl, baseDir + fileName)).start();
            }

            // downloadUsingStream(url, "D:/users/maxsu/sitemap_stream.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void downloadUsingStream(String urlStr, String file) throws IOException {
        URL url = new URL(urlStr);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int count = 0;
        while ((count = bis.read(buffer, 0, 1024)) != -1) {
            fis.write(buffer, 0, count);
        }
        fis.close();
        bis.close();
    }

    private static void downloadUsingNIO(String urlStr, String file) {
        try {
            URL url = new URL(urlStr);
            ReadableByteChannel rbc = Channels.newChannel(url.openStream());
            FileOutputStream fos = new FileOutputStream(file);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            rbc.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}

